<?php

declare(strict_types=1);

namespace app\common\tool\excel;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;

class Export
{
    /**
     * 数据导入
     * @param $url
     * @param $reader_name
     * @return array
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    public static function excelImport($url, $reader_name)
    {
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($reader_name);
        // $reader->setReadDataOnly(); //只读取数据，不读取格式
        $spreadsheet = $reader->load($url); //载入excel表格

        $sheet = $spreadsheet->getActiveSheet();
        $highestRow = $sheet->getHighestRow(); // 总行数
        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return ['code' => -1, 'msg' => '导入数据为空！'];
        }
        $sheet = $spreadsheet->getActiveSheet();
        $res  = array();
        $imglist = [];
        // 遍历所有的多媒体元素（图片）
        $url = 'uploads/image/' . date('Ymd') . '/';
        if (!file_exists('./' . $url)) {
            mkdir('./' . $url, 0777, true);
        }
        foreach ($sheet->getDrawingCollection() as $drawing) {
            if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing) {
                if ($drawing->getIndexedFilename()) {
                    $drawing->getIndexedFilename(); // 获取文件名
                    $imageFilePath = $url . $drawing->getIndexedFilename();
                    list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                    $imglist[$startRow][] = '/' . $imageFilePath;
                    // 将图片保存到指定路径
                    switch ($drawing->getExtension()) {
                        case 'png':
                            $image = imagecreatefrompng($drawing->getPath());
                            imagepng($image, $imageFilePath);
                            break;
                        case 'gif':
                            $image = imagecreatefromgif($drawing->getPath());
                            imagegif($image, $imageFilePath);
                            break;
                        case 'jpg':
                        case 'jpeg':
                            $image = imagecreatefromjpeg($drawing->getPath());
                            imagejpeg($image, $imageFilePath);
                            break;
                    }
                    /**
                     * 压缩图片
                     */
                    self::_openImage($imageFilePath);
                }
            }
        }
        // // 获取行数据
        foreach ($sheet->getRowIterator(2) as $row) {  // 从第二行开始
            $tmp = array();
            // 循环列
            foreach ($row->getCellIterator() as $k => $cell) {
                if ($k == 'C') {
                    $img = empty($imglist[$row->getRowIndex()]) ? '' : $imglist[$row->getRowIndex()];
                    $tmp[] = $img;
                } else {
                    $tmp[] = $cell->getFormattedValue(); //获取单元格的值
                }
            }
            if (!empty($tmp)) {
                $res[$row->getRowIndex()] = $tmp;
            }
        }
        return ['code' => 1, 'data' => $res, 'msg' => '导入成功'];
    }

    /**
     * 导出数据
     */
    public static function export($datatitle, $datalist, $filePath)
    {
        /**
         * 边框样式
         */
        $borders = [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER,
            ],
            'borders' => [
                'outline' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['argb' => '000000'],
                ],
                'inside' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['argb' => '000000'],
                ]
            ],
        ];
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 自定义表头
        $r = range('A', 'C');
        $az = range('A', 'Z');
        foreach ($r as $k => $v) {
            foreach ($az as $vv) {
                $list[] = $v . $vv;
            }
        }
        $cellName = array_merge($az, $list);
        // 设置表头
        foreach ($cellName as $key => $header) {
            $sheet->getRowDimension(1)->setRowHeight(30); //序号高度
            $sheet->getColumnDimension($header)->setWidth(25);
        }
        /**设置表头*/
        foreach ($datatitle as $key => $header) {
            $sheet->setCellValue($cellName[$key] . '1', $header);
            $sheet->getStyle($cellName[$key] . '1')->applyFromArray($borders,);
        }
        /**数据写入 */
        $column = 2;
        foreach ($datalist as $key => $rows) { // 行写入
            $sheet->getRowDimension($column)->setRowHeight(30); //序号高度
            foreach ($rows as $keyName => $value) { // 列写入
                $sheet->setCellValue($cellName[($keyName)] . $column, $value);
                $sheet->getStyle($cellName[($keyName)] . $column)->applyFromArray($borders)->getAlignment()->setWrapText(true);
            }
            $column++;
        }
        // 创建Xlsx文件写入器
        $writer = new Xlsx($spreadsheet);

        if (file_exists($filePath)) {
            unlink('./' . $filePath);
        }
        $writer->save($filePath);
        return '/' . $filePath;
    }
    /**
     * 图片压缩
     */
    public static function _openImage($src)

    {

        list($width, $height, $type, $attr) = getimagesize($src);

        $imageinfo = array(

            'width' => $width,

            'height' => $height,

            'type' => image_type_to_extension($type, false),

            'attr' => $attr

        );

        $fun = "imagecreatefrom" . $imageinfo['type'];
        $images = $fun($src);
        self::_thumpImage($imageinfo, $images, $src);
    }

    /**
     *图片处理
     */

    public static function _thumpImage($imageinfo, $image, $src)

    {
        if ($imageinfo['width'] > 2000) {
            $bl = 0.2;
        } else if ($imageinfo['width'] <= 2000 && $imageinfo['width'] > 1000) {
            $bl = 0.4;
        } else if ($imageinfo['width'] <= 1000 && $imageinfo['width'] > 500) {
            $bl = 0.6;
        } else if ($imageinfo['width'] <= 500 && $imageinfo['width'] > 400) {
            $bl = 0.7;
        } else {
            $bl = 1;
        }
        $new_width = intval($imageinfo['width'] * $bl);

        $new_height = intval($imageinfo['height'] * $bl);

        $image_thump = imagecreatetruecolor($new_width, $new_height);

        imagealphablending($image_thump, false); //这里很重要,意思是不合并颜色,直接用$image_thump图像颜色替换,包括透明色;
        imagesavealpha($image_thump, true); //这里很重要,意思是不要丢了$image_thump图像的透明色;


        //将原图复制带图片载体上面，并且按照一定比例压缩,极大的保持了清晰度

        imagecopyresampled($image_thump, $image, 0, 0, 0, 0, $new_width, $new_height, $imageinfo['width'], $imageinfo['height']);

        imagedestroy($image);
        self::_saveImage('./' . $src, $src, $imageinfo, $image_thump);
    }
    /**
     * 保存压缩图片
     */
    public static function _saveImage($dstImgName, $src, $imageinfo, $image)
    {
        if (empty($dstImgName)) return false;
        $allowImgs = ['.jpg', '.jpeg', '.png', '.bmp', '.wbmp', '.gif'];   //如果目标图片名有后缀就用目标图片扩展名 后缀，如果没有，则用源图的扩展名
        $dstExt = strrchr($dstImgName, ".");
        $sourseExt = strrchr($src, ".");
        if (!empty($dstExt)) $dstExt = strtolower($dstExt);
        if (!empty($sourseExt)) $sourseExt = strtolower($sourseExt);
        //有指定目标名扩展名
        if (!empty($dstExt) && in_array($dstExt, $allowImgs)) {
            $dstName = $dstImgName;
        } elseif (!empty($sourseExt) && in_array($sourseExt, $allowImgs)) {
            $dstName = $dstImgName . $sourseExt;
        } else {
            $dstName = $dstImgName . $imageinfo['type'];
        }
        imagedestroy($image);
        $funcs = "image" . $imageinfo['type'];
        return $funcs($image, $dstName);
    }
}
